$(document).ready(function() {
    let currentPage = 1;
    let pageSize = 10;

    // 全局变量
    let selectedIds = [];
    let currentAction = '';
    
    // 初始化页面
    initPage();
    
    // 初始化函数
    function initPage() {
        loadSensitiveWords();
        bindEvents();
    }
    /**
     * 渲染分页控件
     * @param {number} total - 总记录数
     * @param {number} currentPage - 当前页码
     * @param {number} pageSize - 每页条数
     */
    function renderPagination(total, currentPage, pageSize) {
        const totalPages = Math.ceil(total / pageSize);
        const paginationContainer = $('#paginationContainer'); // 分页容器
        
        // 清空现有分页
        paginationContainer.empty();
        
        // 上一页按钮
        const prevDisabled = currentPage === 1 ? 'disabled' : '';
        paginationContainer.append(`
            <button class="w-8 h-8 flex items-center justify-center rounded border border-neutral-200 text-neutral-400 hover:border-primary hover:text-primary disabled:opacity-50 pagination-btn" 
                    data-page="${currentPage - 1}" ${prevDisabled}>
                <i class="fa fa-angle-left"></i>
            </button>
        `);
        
        // 页码按钮（最多显示5个页码）
        let startPage = Math.max(1, currentPage - 2);
        let endPage = Math.min(totalPages, startPage + 4);
        
        // 调整显示范围
        if (endPage - startPage < 4 && totalPages > 5) {
            startPage = Math.max(1, endPage - 4);
        }
        
        for (let i = startPage; i <= endPage; i++) {
            const isActive = i === currentPage ? 'border-primary bg-primary text-white' : 'border-neutral-200 text-neutral-700 hover:border-primary hover:text-primary';
            paginationContainer.append(`
                <button class="w-8 h-8 flex items-center justify-center rounded ${isActive} pagination-btn" data-page="${i}">
                    ${i}
                </button>
            `);
        }
        
        // 下一页按钮
        const nextDisabled = currentPage === totalPages ? 'disabled' : '';
        paginationContainer.append(`
            <button class="w-8 h-8 flex items-center justify-center rounded border border-neutral-200 text-neutral-400 hover:border-primary hover:text-primary disabled:opacity-50 pagination-btn" 
                    data-page="${currentPage + 1}" ${nextDisabled}>
                <i class="fa fa-angle-right"></i>
            </button>
        `);
        
        // 更新分页信息
        const start = total > 0 ? (currentPage - 1) * pageSize + 1 : 0;
        const end = Math.min(currentPage * pageSize, total);
        $('.pagenation').text(`显示 ${start} 至 ${end} 条，共 ${total} 条`);
    }
    /**
     * 获取筛选参数
     */
    function getFilterParams() {
        return {
            page: currentPage,
            pageSize: pageSize,
            level: $('#levelFilter').val(),
            wordType: $('#wordTypeFilter').val(),
            matchMode: $('#matchModeFilter').val(),
            status: $('#statusFilter').val().trim(),
            keyword: $('#keywordSearch').val().trim()
        };
    }
    /**
     * 获取举报列表
     * @param {*} params 
     * @returns 
     * */
    async function fetchCollectionList(params) {
        try {
            // 构建查询字符串
            const queryParams = new URLSearchParams();
            Object.entries(params).forEach(([key, value]) => {
                if (value !== undefined && value !== null && value !== '') {
                    queryParams.append(key, value);
                }
            });

            // 发起请求
            const response = await fetch(`/system/GetSensitiveWordList?${queryParams.toString()}`, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    // 根据实际需求添加认证信息
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                }
            });
            if (response.status/1 != 200) {
                throw new Error(`请求失败: ${response.statusText}`);
            }

            const data = await response.json();
            return data;
        } catch (error) {
            showToast(error.message || '获取媒体内容列表失败');
        }
    }
    // 加载敏感词列表
    function loadSensitiveWords() {
        // 显示加载中状态
        $('#sensitiveWordTableBody').html('<tr><td colspan="12" class="text-center py-4">加载中...</td></tr>');
        
        // 获取筛选参数
        const params = getFilterParams();
        console.log(params);
        // 调用后端接口获取数据
        fetchCollectionList(params)
            .then(result => {
                renderWordTable(result.data.list);
                renderPagination(result.data.total, currentPage, pageSize);
            })
            .catch(error => {
                // console.error('加载数据失败:', error);
                $('#sensitiveWordTableBody').html('<tr><td colspan="12" class="text-center py-4 text-danger">加载数据失败，请重试</td></tr>');
            });
    }
    
    // 渲染敏感词表格
    function renderWordTable(data) {
        const tableBody = $('#sensitiveWordTableBody');
        tableBody.empty();
        
        if (data.length === 0) {
            tableBody.append(`
                <tr>
                    <td colspan="12" class="px-5 py-10 text-center text-neutral-500">
                        <i class="fa fa-search-minus text-2xl mb-2"></i>
                        <p>没有找到匹配的敏感词</p>
                    </td>
                </tr>
            `);
            return;
        }
        
        data.forEach(item => {
            const typeText = getWordTypeText(item.word_type/1);
            const levelText = getLevelText(item.level/1);
            const levelClass = item.level/1 === 3 ? 'bg-danger/10 text-danger' : 
                             (item.level/1 === 2 ? 'bg-warning/10 text-warning' : 'bg-neutral-100 text-neutral-600');
            const matchModeText = item.match_mode/1 === 1 ? '精确匹配' : '模糊匹配';
            const statusText = item.status/1 === 1 ? '启用' : '禁用';
            const statusClass = item.status/1 === 1 ? 'bg-success/10 text-success' : 'bg-neutral-100 text-neutral-500';
            
            const row = $(`
                <tr>
                    <td class="px-5 py-4">
                        <input type="checkbox" class="word-checkbox rounded border-neutral-300 text-primary focus:ring-primary" data-id="${item.id}">
                    </td>
                    <td class="px-5 py-4 text-sm">${item.id}</td>
                    <td class="px-5 py-4 font-medium">${item.word}</td>
                    <td class="px-5 py-4 text-sm">${item.word_alias || '-'}</td>
                    <td class="px-5 py-4 text-sm">${typeText}</td>
                    <td class="px-5 py-4">
                        <span class="px-2 py-1 text-xs rounded-full ${levelClass}">${levelText}</span>
                    </td>
                    <td class="px-5 py-4 text-sm">${matchModeText}</td>
                    <td class="px-5 py-4 text-sm">${item.replace_str}</td>
                    <td class="px-5 py-4 text-sm">${item.business_scope || '-'}</td>
                    <td class="px-5 py-4">
                        <span class="px-2 py-1 text-xs rounded-full ${statusClass}">${statusText}</span>
                    </td>
                    <td class="px-5 py-4 text-sm text-neutral-500">${item.created_at}</td>
                    <td class="px-5 py-4">
                        <div class="flex space-x-1">
                            <button class="text-primary hover:text-primary/80 p-1" title="编辑" data-action="edit" data-id="${item.id}">
                                <i class="fa fa-pencil"></i>
                            </button>
                            <button class="text-neutral-500 hover:text-neutral-700 p-1 ${item.status/1 === 1 ? 'text-neutral-500' : 'text-success'}" title="${item.status/1 === 1 ? '禁用' : '启用'}" data-action="${item.status/1 === 1 ? 'disable' : 'enable'}" data-id="${item.id}">
                                <i class="${item.status/1 === 1 ? 'fa fa-ban' : 'fa fa-check-circle'}"></i>
                            </button>
                            <button class="text-danger hover:text-danger/80 p-1" title="删除" data-action="delete" data-id="${item.id}">
                                <i class="fa fa-trash"></i>
                            </button>
                        </div>
                    </td>
                </tr>
            `);
            
            tableBody.append(row);
        });
        
        // 重新绑定复选框事件
        bindCheckboxEvents();
    }
    
    // 绑定所有事件
    function bindEvents() {
        // 筛选和搜索事件
        $('#filterBtn').click(applyFilters);
        $('#resetBtn').click(resetFilters);
        $('#searchBtn').click(applySearch);
        $('#keywordSearch').keypress(function(e) {
            if (e.which === 13) applySearch();
        });
        
        // 添加敏感词按钮
        $('#addWordBtn').click(showAddWordModal);
        
        // 模态框按钮事件
        $('#cancelWordBtn').click(hideWordModal);
        $('#wordForm').submit(saveWord);
        
        // 确认模态框事件
        $('#cancelConfirmBtn').click(hideConfirmModal);
        $('#doConfirmBtn').click(doConfirmAction);
        
        // 批量操作按钮
        $('#batchEnableBtn').click(() => showConfirmModal('批量启用', '您确定要启用选中的敏感词吗？', 'batchEnable'));
        $('#batchDisableBtn').click(() => showConfirmModal('批量禁用', '您确定要禁用选中的敏感词吗？', 'batchDisable'));
        $('#batchDeleteBtn').click(() => showConfirmModal('批量删除', '您确定要删除选中的敏感词吗？此操作不可撤销。', 'batchDelete'));
        // 分页按钮点击事件
        $(document).on('click', '.pagination-btn', function() {
            const page = parseInt($(this).data('page'));
            if (!isNaN(page) && page !== currentPage) {
                currentPage = page;
                loadSensitiveWords()
            }
        });
        // 导入导出按钮
        $('#importBtn').click(showImportModal);
        $('#exportBtn').click(exportSensitiveWords);
        $('#cancelImportBtn').click(hideImportModal);
        $('#confirmImportBtn').click(importSensitiveWords);
        
        // 上传区域事件
        $('#uploadArea').click(() => $('#fileUpload').click());
        $('#fileUpload').change(handleFileUpload);
        $('#removeFile').click(removeFile);
        
        // 表格行操作事件委托
        $('#sensitiveWordTableBody').on('click', 'button', function() {
            const action = $(this).data('action');
            const id = $(this).data('id');
            
            switch(action) {
                case 'edit':
                    editWord(id);
                    break;
                case 'enable':
                    showConfirmModal('启用敏感词', '您确定要启用此敏感词吗？', 'enable', id);
                    break;
                case 'disable':
                    showConfirmModal('禁用敏感词', '您确定要禁用此敏感词吗？', 'disable', id);
                    break;
                case 'delete':
                    showConfirmModal('删除敏感词', '您确定要删除此敏感词吗？此操作不可撤销。', 'delete', id);
                    break;
            }
        });
    }
    
    // 绑定复选框事件
    function bindCheckboxEvents() {
        // 全选/取消全选
        $('#selectAll').change(function() {
            const checked = $(this).is(':checked');
            $('.word-checkbox').prop('checked', checked);
            
            // 更新选中ID数组
            selectedIds = checked ? 
                $('.word-checkbox').map((i, el) => $(el).data('id')).get() : 
                [];
            
            updateBatchButtons();
        });
        
        // 单个复选框事件
        $('.word-checkbox').change(function() {
            const id = $(this).data('id');
            const checked = $(this).is(':checked');
            
            if (checked) {
                selectedIds.push(id);
            } else {
                selectedIds = selectedIds.filter(item => item !== id);
                $('#selectAll').prop('checked', false);
            }
            
            updateBatchButtons();
        });
    }
    
    // 更新批量操作按钮状态
    function updateBatchButtons() {
        const hasSelection = selectedIds.length > 0;
        $('#batchEnableBtn').prop('disabled', !hasSelection);
        $('#batchDisableBtn').prop('disabled', !hasSelection);
        $('#batchDeleteBtn').prop('disabled', !hasSelection);
        $('#selectedCount').text(`已选择 ${selectedIds.length} 项`);
    }
    
    // 显示添加敏感词模态框
    function showAddWordModal() {
        $('#modalTitle').text('添加敏感词');
        $('#wordForm')[0].reset();
        $('#wordId').val('');
        $('#replaceStr').val('*');
        $('#level').val(2);
        $('#matchMode').val(1);
        $('#status').val(1);
        $('#wordModal').removeClass('hidden').addClass('flex');
    }
    
    // 隐藏敏感词模态框
    function hideWordModal() {
        $('#wordModal').removeClass('flex').addClass('hidden');
    }
    /**
     * 获取敏感词详情
     * @param {*} id 
     * @returns 
     */
    async function getWord(id){
        try {
            let url = '';

            url = '/system/GetSensitiveWordDetail?id='+id;

            const response = await fetch(url, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                }
            });

            const result = await response.json();
            
            if (!response.ok || result.status/1 !== 0) {
                throw new Error(result.msg || `操作失败: ${response.statusText}`);
            }
            
            return result.data;
        } catch (error) {
            throw error; // 抛出错误给调用方处理
        }
    }
    // 编辑敏感词
    async function editWord(id) {
        
        let word = await getWord(id);
        
        // 填充表单
        $('#modalTitle').text('编辑敏感词');
        $('#wordId').val(word.id);
        $('#word').val(word.word);
        $('#wordAlias').val(word.word_alias);
        $('#wordType').val(word.word_type);
        $('#level').val(word.level);
        $('#matchMode').val(word.match_mode);
        $('#replaceStr').val(word.replace_str);
        $('#status').val(word.status);
        $('#businessScope').val(word.business_scope);
        $('#remark').val(word.remark);
        
        $('#wordModal').removeClass('hidden').addClass('flex');
    }
    
    // 保存敏感词
    function saveWord(e) {
        e.preventDefault();
        
        // 获取表单数据
        const formData = {
            id: $('#wordId').val(),
            word: $('#word').val().trim(),
            word_alias: $('#wordAlias').val().trim(),
            word_type: $('#wordType').val(),
            level: $('#level').val(),
            match_mode: $('#matchMode').val(),
            replace_str: $('#replaceStr').val().trim(),
            status: $('#status').val(),
            business_scope: $('#businessScope').val().trim(),
            remark: $('#remark').val().trim()
        };
        
        // 简单验证
        if (!formData.word) {
            showToast('请输入敏感词内容', 'error');
            return;
        }
        
        if (!formData.word_type) {
            showToast('请选择敏感类型', 'error');
            return;
        }

        // 保存敏感词
        saveForm(formData).then(() => {
            hideWordModal();
            showToast(formData.id ? '敏感词更新成功' : '敏感词添加成功', 'success');
            loadSensitiveWords(); // 重新加载列表
        }).catch((error) => {
            showToast(error.message, 'error');
        });
    }
    
    // 显示确认模态框
    function showConfirmModal(title, message, action, id = null) {
        currentAction = {
            type: action,
            id: id
        };
        
        $('#confirmTitle').text(title);
        $('#confirmMessage').text(message);
        $('#confirmModal').removeClass('hidden').addClass('flex');
    }
    
    // 隐藏确认模态框
    function hideConfirmModal() {
        $('#confirmModal').removeClass('flex').addClass('hidden');
        currentAction = '';
    }
    
    // 切换敏感词状态
    async function ChangeStatus(id,status) {
        try {
            let url = '';

            url = '/system/ToggleSensitiveWordStatus';
            const requestData = {
                id: id,
                status: status
            };
            const response = await fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                },
                body: JSON.stringify(requestData)
            });

            const result = await response.json();
            
            if (!response.ok || result.status/1 !== 0) {
                throw new Error(result.msg || `操作失败: ${response.statusText}`);
            }
            
            return result.data;
        } catch (error) {
            throw error; // 抛出错误给调用方处理
        }
    }
    /**
    * 批量操作
    * @param {*} ids 敏感词id数组
    * @param {*} status 状态
    * @param {*} action 操作类型 batchEnable/batchDisable/batchDelete
    */
    async function BatchOperate(ids,status,action) {
        try {
            let url = '';
            if (action === 'batchDelete') {
                url = '/system/DeleteSensitiveWord';
            } else {
                url = '/system/BatchToggleSensitiveWordStatus';
            }
            const requestData = {
                ids: ids,
                status: status
            };
            const response = await fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                },
                body: JSON.stringify(requestData)
            });

            const result = await response.json();
            
            if (!response.ok || result.status/1 !== 0) {
                throw new Error(result.msg || `操作失败: ${response.statusText}`);
            }
            
            return result.data;
        } catch (error) {
            throw error; // 抛出错误给调用方处理
        }
    }
    /**
     * 保存敏感词
     * @param {*} params 敏感词参数
     */
    async function saveForm(params){
        try {
            let url = '';
            if (params.id) {
                url = '/system/EditSensitiveWord';
            } else {
                url = '/system/AddSensitiveWord';
            }
            const requestData = params;
            const response = await fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                },
                body: JSON.stringify(requestData)
            });
    
            const result = await response.json();
            
            if (!response.ok || result.status/1 !== 0) {
                throw new Error(result.msg || `操作失败: ${response.statusText}`);
            }
            
            return result.data;
        } catch (error) {
            throw error; // 抛出错误给调用方处理
        }
    }
    // 执行确认操作
    function doConfirmAction() {
        if (!currentAction) return;
        
        const { type, id } = currentAction;
        let successMsg = '';
        
        // 模拟操作
        switch(type) {
            case 'enable':
                successMsg = id ? '敏感词已启用' : '选中的敏感词已启用';
                ChangeStatus(id,1).then(() => {
                    hideConfirmModal();
                    showToast(successMsg, 'success');
                    loadSensitiveWords(); // 重新加载列表
                    selectedIds = [];
                    updateBatchButtons();
                    $('#selectAll').prop('checked', false);
                });
                break;
            case 'disable':
                successMsg = id ? '敏感词已禁用' : '选中的敏感词已禁用';
                ChangeStatus(id,0).then(() => {
                    hideConfirmModal();
                    showToast(successMsg, 'success');
                    loadSensitiveWords(); // 重新加载列表
                    selectedIds = [];
                    updateBatchButtons();
                    $('#selectAll').prop('checked', false);
                });
                break;
            case 'delete':
                successMsg = id ? '敏感词已删除' : '选中的敏感词已删除';
                BatchOperate([id],0,'batchDelete').then(() => {
                    hideConfirmModal();
                    showToast(successMsg, 'success');
                    loadSensitiveWords(); // 重新加载列表
                    selectedIds = [];
                    updateBatchButtons();
                    $('#selectAll').prop('checked', false);
                }).catch((error) => {
                    showToast(error.message, 'error');
                });
                break;
            case 'batchEnable':
                successMsg = '选中的敏感词已启用';
                BatchOperate(selectedIds,1,'batchEnable').then(() => {
                    hideConfirmModal();
                    showToast(successMsg, 'success');
                    loadSensitiveWords(); // 重新加载列表
                    selectedIds = [];
                    updateBatchButtons();
                    $('#selectAll').prop('checked', false);
                }).catch((error) => {
                    showToast(error.message, 'error');
                });
                break;
            case 'batchDisable':
                successMsg = '选中的敏感词已禁用';
                BatchOperate(selectedIds,0,'batchDisable').then(() => {
                    hideConfirmModal();
                    showToast(successMsg, 'success');
                    loadSensitiveWords(); // 重新加载列表
                    selectedIds = [];
                    updateBatchButtons();
                }).catch((error) => {
                    showToast(error.message, 'error');
                });
                break;
            case 'batchDelete':
                successMsg = '选中的敏感词已删除';
                BatchOperate(selectedIds,0,'batchDelete').then(() => {
                    hideConfirmModal();
                    showToast(successMsg, 'success');
                    loadSensitiveWords(); // 重新加载列表
                    selectedIds = [];
                    updateBatchButtons();
                }).catch((error) => {
                    showToast(error.message, 'error');
                });
                break;
        }
        
        setTimeout(() => {
            hideConfirmModal();
            showToast(successMsg, 'success');
            loadSensitiveWords(); // 重新加载列表
            selectedIds = [];
            updateBatchButtons();
            $('#selectAll').prop('checked', false);
        }, 500);
    }
    
    // 显示导入模态框
    function showImportModal() {
        $('#fileUpload').val('');
        $('#fileInfo').addClass('hidden');
        $('#importModal').removeClass('hidden').addClass('flex');
    }
    
    // 隐藏导入模态框
    function hideImportModal() {
        $('#importModal').removeClass('flex').addClass('hidden');
    }
    
    // 处理文件上传
    function handleFileUpload(e) {
        const file = e.target.files[0];
        if (file) {
            $('#fileName').text(file.name);
            $('#fileInfo').removeClass('hidden');
        }
    }
    
    // 移除上传文件
    function removeFile() {
        $('#fileUpload').val('');
        $('#fileInfo').addClass('hidden');
    }
    
    // 导入敏感词
    function importSensitiveWords() {
        const file = $('#fileUpload')[0].files[0];
        if (!file) {
            showToast('请选择要导入的文件', 'error');
            return;
        }
        
        // 模拟导入操作
        setTimeout(() => {
            hideImportModal();
            showToast('敏感词导入成功', 'success');
            loadSensitiveWords(); // 重新加载列表
        }, 1000);
    }
    
    // 导出敏感词
    function exportSensitiveWords() {
        // 模拟导出操作
        showToast('正在导出敏感词...', 'info');
        setTimeout(() => {
            showToast('敏感词导出成功', 'success');
        }, 1000);
    }
    
    // 应用筛选
    function applyFilters() {
        // 模拟筛选操作
        showToast('筛选条件已应用', 'info');
        loadSensitiveWords();
    }
    
    // 重置筛选
    function resetFilters() {
        $('#wordTypeFilter').val('');
        $('#levelFilter').val('');
        $('#statusFilter').val('');
        $('#matchModeFilter').val('');
        $('#keywordSearch').val('');
        
        showToast('筛选条件已重置', 'info');
        loadSensitiveWords();
    }
    
    // 应用搜索
    function applySearch() {
        const keyword = $('#keywordSearch').val().trim();
        if (keyword) {
            showToast(`正在搜索: ${keyword}`, 'info');
        } else {
            showToast('请输入搜索关键词', 'warning');
            return;
        }
        
        loadSensitiveWords();
    }
    
    // 辅助函数：获取敏感类型文本
    function getWordTypeText(type) {
        const types = {
            1: '色情低俗',
            2: '暴力恐怖',
            3: '政治敏感',
            4: '辱骂攻击',
            5: '广告营销',
            6: '其他'
        };
        return types[type] || '未知';
    }
    
    // 辅助函数：获取敏感级别文本
    function getLevelText(level) {
        const levels = {
            1: '低',
            2: '中',
            3: '高'
        };
        return levels[level] || '未知';
    }
    
    // Toast提示函数（复用layout.html中的实现）
    function showToast(message, type = 'info', duration = 3000) {
        // 移除已存在的toast
        $('.toast').remove();
        
        // 创建toast元素
        const toast = $(`
            <div class="toast toast-top-center toast-hidden toast-${type}">
                <i class="fa toast-icon ${getToastIcon(type)}"></i>
                <span>${message}</span>
            </div>
        `);
        
        // 添加到页面
        $('body').append(toast);
        
        // 显示toast
        setTimeout(() => {
            toast.removeClass('toast-hidden');
        }, 10);
        
        // 自动隐藏
        setTimeout(() => {
            toast.addClass('toast-hidden');
            setTimeout(() => {
                toast.remove();
            }, 300);
        }, duration);
    }
    
    // 获取Toast图标
    function getToastIcon(type) {
        switch(type) {
            case 'success': return 'fa-check-circle';
            case 'error': return 'fa-times-circle';
            case 'warning': return 'fa-exclamation-triangle';
            case 'info': return 'fa-info-circle';
            default: return 'fa-info-circle';
        }
    }
});